import {
  isScreenSpreaded
} from "./device.js"

//手机屏
let WIDTH_PHONE_STANDARD = 360; //华为标准宽度是360
var WIDTH_PHONE = 381; //实际宽度对应设计稿360下的宽度
var PHONE_RATIO = 1.0583; //实际宽度与华为标准宽度的比率

//Pad竖屏
let WIDTH_PAD_PORTRAIT_STANDARD = 800; //华为标准宽度是600、640、800，这里采用800
var WIDTH_PAD_PORTRAIT = 288; //实际宽度对应设计稿360下的宽度。360 * PAD_PORTRAIT_RATIO
var PAD_PORTRAIT_RATIO = 0.8; //实际宽度与华为标准宽度的比率。屏幕实际dp值/800

//折叠屏
let WIDTH_SPREADED_STANDARD = 677; //华为标准宽度是677、734，这里采用677
var WIDTH_SPREADED = 374.36; //实际宽度对应设计稿360下的宽度
var SPREADED_RATIO = 1.040; //实际宽度与华为标准宽度的比率

//Pad横屏
// let WIDTH_PAD_LANDSCAPE_STANDARD = 417; //华为标准全屏宽度是1280，华为智慧生活App标准显示区域的宽度是417
let WIDTH_PAD_LANDSCAPE_STANDARD = 423; //华为智慧生活App标准显示区域的宽度是423，目前购买的华为pad对应的全屏宽度是1298.417，
var WIDTH_PAD_LANDSCAPE = 284.26; //实际宽度对应设计稿360下的宽度
var PAD_LANDSCAPE_RATIO = 0.7896; //实际宽度与华为标准宽度的比率

let WIDTH_STANDARD = 360; //设计稿的屏幕宽度，需要与./build/utils.js中配置的remUnit匹配，例如：如果 WIDTH_STANDARD = 750，那么remUnit应该配置为75
let SPREADED_SCREEN_RATIO = 1.25; //折叠屏的最大高宽比，比这个大的就认为是pad，比这个小的就认为是折叠屏
var selectWidth = 0;
var flexibleWidth = 0; //app实际显示区域的宽度
var flexibleHeight = 0; //app实际显示区域的高度
var screenWidth = 0; //设备整屏幕的宽度
var screenHeight = 0; //设备整屏幕的高度
var screenType = 1; //1-Android手机 2-Android Pad 竖屏 3-Android Pad 横屏 4-Android折叠屏 101-iPhone 102-iPad
var screenDescription = "";
var screenDpr = 1; //屏幕的像素密度




let isSpreadOn = 0; //折叠屏开关

var screenResizeListener;

;
(function (win, lib) {
  var doc = win.document;
  var docEl = doc.documentElement;
  var metaEl = doc.querySelector('meta[name="viewport"]');
  var flexibleEl = doc.querySelector('meta[name="flexible"]');
  var dpr = 0;
  var scale = 0;
  var tid;
  var flexible = lib.flexible || (lib.flexible = {});

  if (metaEl) {
    console.warn('将根据已有的meta标签来设置缩放比例');
    var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/);
    if (match) {
      scale = parseFloat(match[1]);
      dpr = parseInt(1 / scale);
    }
  } else if (flexibleEl) {
    var content = flexibleEl.getAttribute('content');
    if (content) {
      var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
      var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);
      if (initialDpr) {
        dpr = parseFloat(initialDpr[1]);
        scale = parseFloat((1 / dpr).toFixed(2));
      }
      if (maximumDpr) {
        dpr = parseFloat(maximumDpr[1]);
        scale = parseFloat((1 / dpr).toFixed(2));
      }
    }
  }

  if (!dpr && !scale) {
    var isAndroid = win.navigator.appVersion.match(/android/gi);
    var isIPhone = win.navigator.appVersion.match(/iphone/gi);
    var devicePixelRatio = win.devicePixelRatio;
    if (isIPhone) {
      // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
      if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
        dpr = 3;
      } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
        dpr = 2;
      } else {
        dpr = 1;
      }
    } else {
      // 其他设备下，仍旧使用1倍的方案
      dpr = 1;
    }
    scale = 1 / dpr;
  }

  docEl.setAttribute('data-dpr', dpr);
  if (!metaEl) {
    metaEl = doc.createElement('meta');
    metaEl.setAttribute('name', 'viewport');
    metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
    if (docEl.firstElementChild) {
      docEl.firstElementChild.appendChild(metaEl);
    } else {
      var wrap = doc.createElement('div');
      wrap.appendChild(metaEl);
      doc.write(wrap.innerHTML);
    }
  }

  function refreshRem() {
    // var width = docEl.getBoundingClientRect().width;
    // var height = docEl.getBoundingClientRect().height;
    // var width = docEl.clientWidth; //app实际显示区域（与下面计算的pWidth的差别是：pad横屏时）
    // var height = docEl.clientHeight; //app实际显示区域（与下面计算的pHeight的差别是：pad横屏时）
    screenWidth = window.screen.width; //设备整个屏幕的宽度
    screenHeight = window.screen.height; //设备整个屏幕的高度

    var width = window.innerWidth; //app实际显示区域（与下面计算的pWidth的差别是：pad横屏时）
    var height = window.innerHeight; //app实际显示区域（与下面计算的pHeight的差别是：pad横屏时）

    if (width == 0 || height == 0) {
      width = screenWidth;
      height = screenHeight;
    }

    flexibleWidth = width;
    flexibleHeight = height;
    screenDpr = dpr;
    var u = navigator.userAgent;
    var isIOS = false;
    if (u.indexOf("Mac OS X") > -1) {
      isIOS = true;
    } else {
      isIOS = false;
    }
    if (isIOS) {
      if (width / dpr > 600) {
        //iPad
        PAD_PORTRAIT_RATIO = width / WIDTH_PAD_PORTRAIT_STANDARD;
        WIDTH_PAD_PORTRAIT = PAD_PORTRAIT_RATIO * WIDTH_STANDARD;
        width = WIDTH_PAD_PORTRAIT;
        selectWidth = width;
        screenType = 102;
        screenDescription = "flexible判断为：iPad";
      } else {
        //iPhone
        PHONE_RATIO = width / WIDTH_PHONE_STANDARD;
        WIDTH_PHONE = PHONE_RATIO * WIDTH_STANDARD;
        width = WIDTH_PHONE;
        selectWidth = width;
        screenType = 101;
        screenDescription = "flexible判断为：iPhone";
      }
    } else {
      if (screenWidth / dpr >= 600) {
        // if (flexibleWidth / dpr < 600) {
        //   //android普通手机屏
        //   PHONE_RATIO = width / WIDTH_PHONE_STANDARD;
        //   WIDTH_PHONE = PHONE_RATIO * WIDTH_STANDARD;
        //   width = WIDTH_PHONE;
        //   selectWidth = width;
        //   screenType = 1;
        //   screenDescription = "flexible判断为：android手机屏";
        // } else {
        if (screenWidth > screenHeight) {
          //pad横屏
          PAD_LANDSCAPE_RATIO = width / WIDTH_PAD_LANDSCAPE_STANDARD;
          WIDTH_PAD_LANDSCAPE = PAD_LANDSCAPE_RATIO * WIDTH_STANDARD;
          width = WIDTH_PAD_LANDSCAPE;
          selectWidth = width;
          screenType = 3;
          screenDescription = "flexible判断为：pad横屏";
        } else {
          if (1.0 * screenHeight / screenWidth < SPREADED_SCREEN_RATIO) {
            //android折叠屏
            SPREADED_RATIO = width / WIDTH_SPREADED_STANDARD;
            WIDTH_SPREADED = SPREADED_RATIO * WIDTH_STANDARD;
            width = WIDTH_SPREADED;
            selectWidth = width;
            screenType = 4;
            screenDescription = "flexible判断为：折叠屏";
          } else {
            //pad竖屏
            PAD_PORTRAIT_RATIO = width / WIDTH_PAD_PORTRAIT_STANDARD;
            WIDTH_PAD_PORTRAIT = PAD_PORTRAIT_RATIO * WIDTH_STANDARD;
            width = WIDTH_PAD_PORTRAIT;
            selectWidth = width;
            screenType = 2;
            screenDescription = "flexible判断为：pad竖屏";
          }
        }
        // }
      } else {
        if (1.0 * flexibleHeight / flexibleWidth < SPREADED_SCREEN_RATIO) {
          //android折叠屏
          SPREADED_RATIO = width / WIDTH_SPREADED_STANDARD;
          WIDTH_SPREADED = SPREADED_RATIO * WIDTH_STANDARD;
          width = WIDTH_SPREADED;
          selectWidth = width;
          screenType = 4;
          screenDescription = "flexible判断为：折叠屏";
        } else {
          //android普通手机屏
          PHONE_RATIO = width / WIDTH_PHONE_STANDARD;
          WIDTH_PHONE = PHONE_RATIO * WIDTH_STANDARD;
          width = WIDTH_PHONE;
          selectWidth = width;
          screenType = 1;
          screenDescription = "flexible判断为：android手机屏";
        }
      }
    }
    var rem = width / 10;
    docEl.style.fontSize = rem + 'px';
    flexible.rem = win.rem = rem;
  }

  win.addEventListener('resize', function () {
    clearTimeout(tid);
    tid = setTimeout(function () {
      // 需要执行的代码
      refreshRem();
      if (screenResizeListener != null) {
        screenResizeListener(screenType);
      }
    }, 500);
  }, false);
  win.addEventListener('pageshow', function (e) {
    if (e.persisted) {
      clearTimeout(tid);
      tid = setTimeout(refreshRem, 300);
    }
  }, false);

  if (doc.readyState === 'complete') {
    doc.body.style.fontSize = 12 * dpr + 'px';
  } else {
    doc.addEventListener('DOMContentLoaded', function (e) {
      doc.body.style.fontSize = 12 * dpr + 'px';
    }, false);
  }


  refreshRem();

  flexible.dpr = win.dpr = dpr;
  flexible.refreshRem = refreshRem;
  flexible.rem2px = function (d) {
    var val = parseFloat(d) * this.rem;
    if (typeof d === 'string' && d.match(/rem$/)) {
      val += 'px';
    }
    return val;
  }
  flexible.px2rem = function (d) {
    var val = parseFloat(d) / this.rem;
    if (typeof d === 'string' && d.match(/px$/)) {
      val += 'rem';
    }
    return val;
  }

})(window, window['lib'] || (window['lib'] = {}));

function isIOS() {
  var u = navigator.userAgent;
  var isIOS = false;
  if (u.indexOf("Mac OS X") > -1) {
    isIOS = true;
  } else {
    isIOS = false;
  }
  return isIOS;
}

// 将设计稿（标准）尺寸转换为不同屏幕对应的尺寸（当需要在代码中动态改变尺寸时使用该函数）
function screenSize(originValue) {
  switch (screenType) {
    case 101: //iPhone
      return parseInt(PHONE_RATIO * originValue);
    case 102: //iPad
      return parseInt(PAD_PORTRAIT_RATIO * originValue);
    case 1: //android手机
      return parseInt(PHONE_RATIO * originValue);
    case 2: //android Pad竖屏
      return parseInt(PAD_PORTRAIT_RATIO * originValue);
    case 3: //android Pad横屏
      return parseInt(PAD_LANDSCAPE_RATIO * originValue);
    case 4: //android 折叠屏
      return parseInt(SPREADED_RATIO * originValue);
  }
}

function itemWidth() {
  //屏幕分为8个item，每个item间距固定为12px
  return (flexibleWidth - screenSize(12.0) * 9) / 8.0;
}

//对话框的柔性布局的对齐方式
function getDialogFlexAlign(screenType) {
  switch (screenType) {
    case 101: //iPhone
      return {
        alignItems: 'flex-end',
          justifyContent: 'center'
      };
    case 102: //iPad
      return {
        alignItems: 'center',
          justifyContent: 'center'
      };
    case 1: //android手机
      return {
        alignItems: 'flex-end',
          justifyContent: 'center'
      };
    case 2: //android Pad竖屏
      return {
        alignItems: 'center',
          justifyContent: 'center'
      };
    case 3: //android Pad横屏
      return {
        alignItems: 'flex-end',
          justifyContent: 'center'
      };
    case 4: //android 折叠屏
      return {
        alignItems: 'center',
          justifyContent: 'center'
      };
  }
}

//对话框
function getDialogStyle(screenType) {
  switch (screenType) {
    case 101: //iPhone
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px", marginBottom: screenSize(16.0) + 'px'
      };
    case 102: //iPad
      //pad竖屏：占据4个等分
      return {
        width: itemWidth() * 4 + screenSize(12.0) * 3 + "px", marginBottom: 0 + 'px'
      };
    case 1: //android手机
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px", marginBottom: screenSize(16.0) + 'px'
      };
    case 2: //android Pad竖屏
      //pad竖屏：占据4个等分
      return {
        width: itemWidth() * 4 + screenSize(12.0) * 3 + "px", marginBottom: 0 + 'px'
      };
    case 3: //android Pad横屏
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px", marginBottom: screenSize(16.0) + 'px'
      };
    case 4: //android 折叠屏
      //折叠屏：占据4个等分
      return {
        width: itemWidth() * 4 + screenSize(12.0) * 3 + "px", marginBottom: 0 + 'px'
      };
    default:
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px", marginBottom: screenSize(16.0) + 'px'
      };
  }
}

//二级页面左右缩进
function getSecondPageStyle(screenType) {
  // console.log("二级页面左右缩进：flexibleWidth = ", flexibleWidth);
  switch (screenType) {
    case 101: //iPhone
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px"
      };
    case 102: //iPad
      //占据6个column
      return {
        width: itemWidth() * 6 + screenSize(12.0) * 5 + "px"
      };
    case 1: //android手机
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px"
      };
    case 2: //android Pad竖屏
      //占据6个column
      return {
        width: itemWidth() * 6 + screenSize(12.0) * 5 + "px"
      };
    case 3: //android Pad横屏
      return {
        width: flexibleWidth - screenSize(12.0) * 2 + "px"
      };
    case 4: //android 折叠屏
      return {
        width: itemWidth() * 6 + screenSize(12.0) * 5 + "px"
      };
  }
}
//单按钮，占据3个column(文字超长，可延长到6个column)
function getSingleButtonStyle(screenType) {
  // console.log("单按钮样式：flexibleWidth = ", flexibleWidth);
  switch (screenType) {
    case 101: //iPhone
      return {
        width: flexibleWidth / 2.0 + "px"
      };
    case 102: //iPad
      return {
        width: itemWidth() * 3 + screenSize(12.0) * 2 + "px"
      };
    case 1: //android手机
      return {
        width: flexibleWidth / 2.0 + "px"
      };
    case 2: //android Pad竖屏
      return {
        width: itemWidth() * 3 + screenSize(12.0) * 2 + "px"
      };
    case 3: //android Pad横屏
      return {
        width: flexibleWidth / 2.0 + "px"
      };
    case 4: //android 折叠屏
      return {
        width: itemWidth() * 3 + screenSize(12.0) * 2 + "px"
      };
  }
}

function setScreenResizeListener(listener) {
  screenResizeListener = listener;
}

export {
  WIDTH_PHONE,
  PHONE_RATIO,
  WIDTH_SPREADED,
  SPREADED_RATIO,
  WIDTH_PAD_PORTRAIT,
  PAD_PORTRAIT_RATIO,
  WIDTH_PAD_LANDSCAPE,
  PAD_LANDSCAPE_RATIO,

  WIDTH_STANDARD,
  SPREADED_SCREEN_RATIO,
  selectWidth,
  flexibleWidth,
  flexibleHeight,
  screenWidth,
  screenHeight,
  screenDpr,
  screenType,
  screenDescription,
  isIOS,
  isSpreadOn,
  screenSize,
  getSecondPageMarginStyle,
  getSecondPageStyle,
  getDialogFlexAlign,
  getDialogStyle,
  getSingleButtonStyle,
  setScreenResizeListener,
  itemWidth,
}
